package com.shj.em.base.entity;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableLogic;
import com.baomidou.mybatisplus.annotations.Version;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.enums.FieldStrategy;
import com.baomidou.mybatisplus.enums.IdType;
import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Date;

@Data
public class BaseEntity {

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 是否删除  1：已删除 0：正常
     */
    @TableLogic
    private Integer delFlag;

    @TableField( fill = FieldFill.INSERT)
    private Date createDt;

    @TableField( fill = FieldFill.INSERT)
    private String createBy;

    @TableField( fill = FieldFill.INSERT_UPDATE)
    private Date updateDt;

    @TableField( fill = FieldFill.INSERT_UPDATE)
    private String updateBy;

    @Version
    private Long version;

    public Serializable key(){
        Field[] fields= this.getClass().getDeclaredFields();
        for (Field field:fields){
            if (field.getAnnotationsByType(TableId.class).length>0){
                try {
                    return (Serializable) BeanUtils.getPropertyDescriptor(this.getClass(),field.getName()).getReadMethod().invoke(this);
                } catch (Exception e) {
                    return null;
                }
            }
        }
        return null;
    }
}
